package com.itheima.mobile.task;

import com.itheima.mobile.service.IsetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Component
@Slf4j
public class SetmealChangeTask {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private IsetmealService setmealService;

    /**
     * 定时检查套餐数据是否变更  每隔2分钟一次
     */
    @Scheduled(cron = "0 */2 * * * ?")
    public void clearDiffData() {
        log.info("--------------定时套餐数据变更检查开始----------------");
        String setmeal_add_update = redisTemplate.opsForValue().get("setmeal_Add_Update");
        if(setmeal_add_update == null){
            log.info("--------------定时套餐数据变更检查结束(无更新数据)----------------");
            return;
        }
        try {
            setmealService.generateSetmealHtml();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("生成套餐静态页面异常!");
        }

        String[] setmealIdArr = setmeal_add_update.split(",");
        //套餐id去重
        List<String> setmealIdList = Arrays.asList(setmealIdArr).stream().distinct().collect(Collectors.toList());
        try {
            setmealService.generateSetmealDetailHtml(setmealIdList);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("生成套餐详情静态页面异常!");
        }
        log.info("变更的套餐id有:{}",setmealIdList);
        log.info("=====静态页面更新成功!====");

        //清除redis中的key
        redisTemplate.delete("setmeal_Add_Update");
        log.info("--------------定时套餐数据变更检查结束----------------");
    }
}
